import {
  getStatisticalTable,
  editStatisticalRecord
} from '../../api/customer'
import {
  STATISTICAL_LIST,
  STATISTICAL_CURRENT_ROW,
  STATISTICAL_DATA_COUNT,
  STATISTICAL_HISTORY_DATA,
  STATISTICAL_UPLOAD_LIST
} from '../motations-type'

export default {
  state: {
    statisticalList: [],
    statisticalDataCount: null,
    pageSize: 20,
    statisticalHistoryData: [],
    row: {
      proid: '',
      cpa: '',
      rz: '',
      uv: '',
      ctime: '',
      yreturn: '',
      return: ''
    }
  },
  getters: {
    statisticalList: state => state.statisticalList
  },
  mutations: {
    [STATISTICAL_LIST] (state, data) {
      state.statisticalList = data
    },
    [STATISTICAL_CURRENT_ROW] (state, data) {
      state.row = data
    },
    [STATISTICAL_DATA_COUNT] (state, data) {
      state.statisticalDataCount = data
    },
    [STATISTICAL_HISTORY_DATA] (state, data) {
      state.statisticalHistoryData = data
    },
    [STATISTICAL_UPLOAD_LIST] (state, data) {
      state.statisticalList = state.statisticalList.push(data)
    }
  },
  actions: {
    async getStatisticalList ({ commit, rootState }, playload) {
      let data = {}
      let newData = []
      if (Object.keys(playload).length > 0) {
        data = playload
      }
      const resp = await getStatisticalTable(data)
      resp.data.data.rows.map((item) => {
        newData = [...newData, {
          id: item.id,
          proid: item.proid,
          proname: item.proname,
          uv: item.uv,
          pname: item.pname,
          ctime: item.ctime,
          cpa: item.cpa,
          rz: item.rz,
          p: item.p,
          f: item.f,
          reqRate: item.reqRate,
          ordRate: item.ordRate,
          return: item.return,
          yreturn: item.yreturn,
          reRate: item.reRate
        }]
      })
      commit(STATISTICAL_LIST, newData)
      commit(STATISTICAL_DATA_COUNT, resp.data.data.total)
      if (newData.length < rootState.statistical.pageSize) {
        commit(STATISTICAL_HISTORY_DATA, newData)
      } else {
        commit(STATISTICAL_HISTORY_DATA, newData.slice(0, rootState.statistical.pageSize))
      }
    },
    async changeStatisticalPage ({ commit, rootState }, index) {
      let data = rootState.statistical.statisticalList
      let _start = (index - 1) * rootState.statistical.pageSize
      let _end = index * rootState.statistical.pageSize
      commit(STATISTICAL_HISTORY_DATA, data.slice(_start, _end))
    },
    async editStatisticalData ({ commit, rootState }, playload) {
      let data = {}
      if (Object.keys(playload).length > 0) {
        data = playload
      }
      await editStatisticalRecord(data)
    },
    async getStatisticalCurrentRow ({ commit, rootState }, row) {
      commit(STATISTICAL_CURRENT_ROW, row)
    },
    async getStatisticalUploadList ({ commit, rootState }, uploadList) {
      commit(STATISTICAL_UPLOAD_LIST, uploadList)
    }
  }
}
